﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;

namespace AuthenticationSection
{
    public class Authentication : IAuthentication
    {
        private static Authentication _Authentication = null;

        public static Authentication GetInstance
        {
            get
            {
                if (_Authentication == null)
                    _Authentication = new Authentication();
                return _Authentication;
            }
        }

        public UserModel LogOn(string userName, string passWord)
        {
            if (ValidatorString(userName) && ValidatorString(passWord))
            {
                string pwdMd5 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(passWord, "MD5").ToLower();
                var info = UserInfo.GetInstance.GetUsers().SingleOrDefault(p => p.UserName == userName && p.PassWord == pwdMd5);
                if (info != null)
                {
                    BillsModel bills = new BillsModel(userName, passWord, DateTime.UtcNow, DateTime.UtcNow.AddMinutes(30), info.Role);
                    string billsEncrypt = EncryptBills(bills);

                    HttpCustomResponse.GetInstance.SaveBillsInCookie(billsEncrypt);
                    if (billsEncrypt.Length < Unit.maxCookieLength)
                    {
                        UserModel user = new UserModel();
                        user.UserName = info.UserName;
                        user.Role = info.Role;
                        return user;
                    }
                }
            }
            return new UserModel();
        }

        //public HttpCookie LogOn(string bills)
        //{
        //    if (!string.IsNullOrEmpty(bills))
        //    {
        //        if (bills.Length < Unit.maxCookieLength)
        //        {
        //            HttpCookie cookie = new HttpCookie(Unit.cookieName, bills);
        //            return cookie;
        //        }
        //    }
        //    return null;
        //}

        public void LogOut()
        {
            if (!string.IsNullOrEmpty(UserInfo.Identity))
            {
                HttpCustomResponse.GetInstance.RemoveBills();
            }
        }

        public bool ChangePassWord(string userSign, string newPwd)
        {
            if (ValidatorString(userSign) && ValidatorString(newPwd))
            {
                var info = UserInfo.GetInstance.GetUsers().SingleOrDefault(p => p.UserName == userSign);
                if (info != null)
                {
                    info.PassWord = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(newPwd, "MD5").ToLower();
                    return true;
                }
            }
            return false;
        }

        private bool ValidatorString(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                string ex = "^[a-zA-Z0-9_]{4,15}$";//允许5-16位的字母数字下划线
                Regex reg = new Regex(ex);
                return reg.IsMatch(str);
            }
            return false;
        }

        /// <summary>
        /// 加密票据信息
        /// </summary>
        /// <param name="bills"></param>
        /// <returns></returns>
        internal static string EncryptBills(BillsModel bills)
        {
            string ciphertext = "";
            string passwordMd5 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(bills.Password, "MD5").ToLower();
            string str = bills.UserName + "|" + passwordMd5 + "|" + bills.IssueDate.ToString() + "|" + bills.ExpirationDate.ToString() + "|" + bills.UserRole;
            byte[] s = System.Text.Encoding.Default.GetBytes(str);
            for (int i = 0; i < str.Length; i++)
            {
                if (s[i] < 16)
                {
                    ciphertext = ciphertext + "0" + s[i].ToString("X") + "'";
                }
                else
                {
                    ciphertext = ciphertext + s[i].ToString("X") + "'";
                }
            }
            return ciphertext;
        }

        /// <summary>
        /// 解密票据信息
        /// </summary>
        /// <param name="str">票据</param>
        /// <returns></returns>
        internal static BillsModel DecryptionBill(string str)
        {
            string[] strArray = str.Split('\'');
            string str2 = "";
            for (int i = 0; i < strArray.Length - 1; i++)
            {
                byte[] b = new byte[] { Convert.ToByte(strArray[i], 16) };
                str2 += System.Text.Encoding.Default.GetString(b);
            }
            string[] s = str2.Split('|');
            return new BillsModel(s[0], s[1], DateTime.Parse(s[2]), DateTime.Parse(s[3]), s[4]);
        }
    }
}
